/**
 * 
 */
package helper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.sql.DataSource;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.frame.common.log.GlobalBase;

//import com.hotshop.common.GlobalBase;



/**
 * 初始化数据库
 * @author alex.lee at 2010-9-15 上午11:03:08
 *
 * desc：
 */
public class SqlFileExecuter extends GlobalBase {

	// 是否初始化数据库
	private boolean init;

	private DataSource dataSource;

	// 执行sql文件
	public boolean execute() {
		if (!init)
			return false;

		String[] sqls = null;
		try {
			sqls = this.getSqls();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (sqls != null) {
			logger.info("Execute sql start.");
			Connection conn = null;
			try {
				conn = dataSource.getConnection();
				Statement stmt = conn.createStatement();
				for (String sql : sqls) {
					if (sql == null || sql.trim().equals(""))
						continue;

					sql = sql.trim().toLowerCase();
					if (sql.startsWith("insert") || sql.startsWith("update")
							|| sql.startsWith("delete"))
						stmt.executeUpdate(sql);
					else
						stmt.execute(sql);
					logger.info("Execute sql: " + sql);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
			logger.info("Execute sql over.");
			try {
				updateProperties();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return true;
	}

	// 获取sql
	private String[] getSqls() throws IOException {
		URL path = this.getClass().getResource("/");
		File f = new File(path.getPath());
		String sqlPath = f.getParent() + File.separator + "sql"
				+ File.separator + "app.sql";

		File sqlF = new File(sqlPath);
		if (!sqlF.exists()) {
			logger.info("Sql file is not exit.");
			return null;
		}

		FileReader fr = new FileReader(sqlF);
		BufferedReader br = new BufferedReader(fr);
		String line = br.readLine();
		StringBuilder sqls = new StringBuilder();
		while (line != null) {
			if (!line.startsWith("--") && !line.startsWith("#")
					&& !line.startsWith("//"))
				sqls.append(line);
			line = br.readLine();
		}
		br.close();
		fr.close();
		String[] sql = sqls.toString().split(";");
		return sql;
	}

	// 将数据初始化默认值置为false
	@SuppressWarnings("unchecked")
	public void updateProperties() throws Exception {
		File f = new File(this.getClass().getResource("/").getPath());
		String path = f.getParent() + File.separator + "conf" + File.separator
				+ "dataAccessContext.xml";
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(path);
		List<Element> list = document.getRootElement().elements();
		for (Element node : list) {
			Attribute attr = node.attribute("id");
			if (attr == null)
				continue;
			String id = attr.getText();
			if (id != null && id.equals("sqlFileExecuter")) {
				List<Element> prolist = node.elements();
				for (Element property : prolist) {
					if (property.attribute("name").getText().equals(
							"init")) {
						property.attribute("value").setText("false");
						XMLWriter output = new XMLWriter(new FileWriter(
								new File(path)));
						output.write(document);
						output.close();
						logger.info("Close datasource initialization.");
						break;
					}
				}
				break;
			}
		}
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public void setInit(boolean init) {
		this.init = init;
	}
}
